'''
女性专属疾病保险
'''
import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper
from urllib.parse import urlencode


class Spider(object):

    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "女性专属疾病保险"

    #生成产品数据
    def genProductInfo(self):

        #年龄段
        year = [str(i) for i in range(18,61)]
        #保障计划 008 基础版 009经典版 010豪华版
        plan = ["51290008","51290009","51290010"]
        for v in product( year,plan ):

            if v[1] == "51290008":

                planCode = "普通版" \

            elif v[1] == "51290009":

                planCode = "经典版" \

            else:

                planCode = "豪华版"

            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format( v[0],planCode,v[1]))
            self.mysql._conn.commit()
            print("%s写入数据库成功"%self.name)

    #执行爬虫
    def requestJson(self,dt=None):

        data = {

            "campaignDefId":"",
            "goodsCode": "83890638",
            "packageDefId": dt["planCode"],
            "campaignId": "10002159158",
            "bf": "{year}-12-20".format( year = str(2019-int(dt["year"]))),
        }
        data = urlencode( data )


        r = requests.get( url = domain[self.name]["url"] + data ,headers=domain[self.name]["header"])

        print( r.json( ))
        if r.status_code == 200 and r.json()["returnCode"] == "success":

            price = Helper.decimalParse( r.json()["returnMsg"])

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }

            self.mysql.updatePrice( data )


        else:

            data = {

                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.randTask(data)

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
